package org.obsidianrad.utils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassPathHacker {

	@SuppressWarnings("unchecked")
	private static final Class[] parameters = new Class[] { URL.class };

	@SuppressWarnings("deprecation")
	public static void addFile(String s) throws IOException {
		File f = new File(s);
		addURL(f.toURL());
	}

	@SuppressWarnings("deprecation")
	public static void addFile(File f) throws IOException {
		addURL(f.toURL());
	}

	@SuppressWarnings("unchecked")
	public static void addURL(URL u) throws IOException {
		if(u.getFile().contains(".svn")){
			return;
		}
		// URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		URLClassLoader sysloader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
		Class sysclass = URLClassLoader.class;

		try {
			Method method = sysclass.getDeclaredMethod("addURL", parameters);
			method.setAccessible(true);
			method.invoke(sysloader, new Object[] { u });
		} catch (Throwable t) {
			t.printStackTrace();
			throw new IOException("Error, could not add URL to system classloader");
		}// end try catch

	}// end method

	public static void addDirectory(File baseDir) throws IOException {
 		String[] jars = baseDir.list();
		for(int k=0; k<jars.length; k++){
			File f = new File(baseDir.getAbsolutePath() + System.getProperty("file.separator") + jars[k]);
			if(f.isDirectory()){
				addDirectory(f);
			} else {
				addFile(f);
			}
		}
	}
	
}// end class